class Solution {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    //根据一棵树的前序遍历与中序遍历构造二叉树
    public int i = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return  bulidTreeChild(preorder,inorder,0,inorder.length-1);
    }
    public TreeNode bulidTreeChild(int[] preorder, int[] inorder, int inbegin, int inend) {
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[i]);
        //找到当前根，在中序遍历的位置
        int rootIndex = findIndex(inorder,inbegin,inend,preorder[i]);
        i++;
        root.left = bulidTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right = bulidTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }
    private int findIndex(int[] inorder,int inbegin,int inend, int key) {
        for(int i = inbegin;i<=inend;i++) {
            if(key == inorder[i]) {
                return i;
            }
        }
        return -1;
    }
}
